package com.xl.serivce.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.xl.serivce.DownloadService;
import com.xl.utils.file.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Service
public class DownloadServiceImpl implements DownloadService {

    @Value("${file.dir}")
    private String saveDir;

    @Override
    public void download(List<String> list) {

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            //如果使用HttpActuator 没有办法通过http获得返回来的 流，因此使用HuTool的 HttpRequest对象
            //HttpActuator httpClient = new HttpActuator("127.0.0.1" , "8890" , "/uploadFile");
            //String post = httpClient.post(JSON.toJSONString(list));

            //使用Hutool的HttpRequest对象发送消息
            HttpRequest body = HttpRequest.post("127.0.0.1:8890/uploadFile").body(JSON.toJSONString(list));
            HttpResponse httpResponse = body.executeAsync(); //请求服务器之后，服务器给我返回了流 ，也返回了一个String ，但是怎么拿到这String呢？
            String resp_msg = httpResponse.body();
            inputStream = httpResponse.bodyStream();
            httpResponse.getFileNameFromDisposition("Location");
            Map<String, List<String>> headers = httpResponse.headers();
            //远程接口可以把文件名放在请求头里面带过来
            String ss = httpResponse.header("Location");

            //准备文件，将输入流写入文件
            FileUtil.noExistCreateDirs(saveDir);
            FileUtil.noExistCreateFile(saveDir + "/test.zip");
            File file = new File(saveDir + "/test.zip");
            fileOutputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            //注意这里是不等于 -1
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
